package com.chinacoal.microservice.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.mapper.*;
import com.chinacoal.microservice.pojo.CcmsSmartleasingCoefficientTemplate;
import com.chinacoal.microservice.pojo.CcmsSmartleasingRoom;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.service.CostFactorTemplateService;
import com.chinacoal.microservice.util.CodeMsg;
import com.chinacoal.microservice.util.QueryCriteria;
import com.chinacoal.microservice.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zhuliang
 * @version V1.0
 * @Description: 费用系数模板-后端实现类
 * @date 2020-12-04 17：40
 */
@Slf4j
@Service
public class CostFactorTemplateServiceImpl implements CostFactorTemplateService {

    @Autowired
    private CcmsSmartleasingCoefficientTemplateMapper coefficientTemplateMapper;

    @Autowired
    private CcmsSmartleasingRoomMapper roomMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @Description: 查询所有的费用系数信息(带分页)
     * @author zhuliang
     * @date 2020/11/25 20:23
     */
    @Override
    public Result<List<CcmsSmartleasingCoefficientTemplate>> getAllCostTemplate(QueryCriteria queryCriteria, String token) {
        //设置分页条件
        Page<CcmsSmartleasingCoefficientTemplate> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页查询
        List<CcmsSmartleasingCoefficientTemplate> templateList = coefficientTemplateMapper.selectPage(toPage, new EntityWrapper<CcmsSmartleasingCoefficientTemplate>().eq("delete_sign", 0).orderBy("last_update_date", false).setSqlSelect("pk_coefficient_template_id","coefficient_name","cost_factor_status"));

        return Result.success(templateList, toPage.getTotal());
    }

    /**
     * @Description: 根据费用系数信息id查询费用系数信息
     * @author zhuliang
     * @date 2020/11/25 20:48
     */
    @Override
    public Result<CcmsSmartleasingCoefficientTemplate> getCostTemplateById(String pkCoefficientTemplateId, Integer status, String token) {
        //根据系数id查询系数信息
        CcmsSmartleasingCoefficientTemplate coefficientTemplate = coefficientTemplateMapper.selectById(pkCoefficientTemplateId);

        //判断是详情的调用，还是修改的调用
        if (1 == status) {
            //查询是否有房间与之关联
            String countByCoefficientId = roomMapper.getCountByCoefficientId(coefficientTemplate.getPkCoefficientTemplateId());
            if (StringUtils.isNotEmpty(countByCoefficientId)) {
                return Result.success(new CodeMsg(30000, "当前有房间正在使用该模板，如修改系数则相关房间收费规则将在下月按最新规则执行收费，是否继续"), coefficientTemplate);
            }
        }

        return Result.success(coefficientTemplate);
    }

    /**
     * @Description: 根据费用系数信息id关闭费用系数
     * @author zhuliang
     * @date 2020/11/26 9:45
     */
    @Override
    public Result closeCoefficient( String pkCoefficientTemplateId, String token) {
        //判断是否有房间与其关联
        String count = roomMapper.getCountByCoefficientId(pkCoefficientTemplateId);
        if (StringUtils.isNotEmpty(count)) {
            log.error(CodeMsg.ROOM_USING_TEMPLATE.toString() + "-->有房间还在使用:" + pkCoefficientTemplateId);
            return Result.error(CodeMsg.ROOM_USING_TEMPLATE);
        }

        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //修改费用系数信息
        coefficientTemplateMapper.updateStatusById(currency.getLoginId(), new Date(), 1, pkCoefficientTemplateId);

        return Result.success();
    }

    /**
     * @Description: 添加费用系数模板信息
     * @author zhuliang
     * @date 2020/11/26 10:05
     */
    @Override
    public Result addCoefficient(CcmsSmartleasingCoefficientTemplate coefficientTemplate, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //完善信息
        coefficientTemplate.setLastUpdateDate(new Date());
        coefficientTemplate.setLastUpdatedBy(currency.getLoginId());
        coefficientTemplate.setCreatedBy(currency.getLoginId());
        coefficientTemplate.setCreationDate(new Date());
        coefficientTemplate.setCostFactorStatus(0);

        //添加信息
        coefficientTemplateMapper.insert(coefficientTemplate);

        return Result.success();
    }

    /**
     * @Description: 费用系数模板的关联房间
     * @author zhuliang
     * @date 2020/11/26 15:40
     */
    @Override
    public Result<List<CcmsSmartleasingRoom>> modifyTheAssociatedRoom(String pkCoefficientTemplateId, String token) {
        //根据模板id查询房间信息
        List<CcmsSmartleasingRoom> rooms = roomMapper.getRoomByCoefficientId(pkCoefficientTemplateId);

        return Result.success(rooms);
    }

    /**
     * @Description: 修改费用信息
     * @author zhuliang
     * @date 2020/11/30 19:00
     */
    @Override
    public Result<CcmsSmartleasingCoefficientTemplate> updateCoefficientTemplate(String token, CcmsSmartleasingCoefficientTemplate coefficientTemplate) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //完善信息
        coefficientTemplate.setLastUpdatedBy(currency.getLoginId());
        coefficientTemplate.setLastUpdateDate(new Date());

        //将垃圾处理费置为空
        if (coefficientTemplate.getGarbageDisposalFee() == null){
            coefficientTemplateMapper.updateGarbageDisposalFeeToNull(coefficientTemplate.getPkCoefficientTemplateId());
        }
        //将电梯费单价置为空
        if (coefficientTemplate.getUnitPriceElevatorFee() == null){
            coefficientTemplateMapper.updateUnitPriceElevatorFeeToNull(coefficientTemplate.getPkCoefficientTemplateId());
        }
        //将卫生费置为空
        if (coefficientTemplate.getSanitationFee() == null){
            coefficientTemplateMapper.updateSanitationFeeToNull(coefficientTemplate.getPkCoefficientTemplateId());
        }
        //将本体维修基金置为空
        if (coefficientTemplate.getMaintenanceFund() == null){
            coefficientTemplateMapper.updateMaintenanceFundToNull(coefficientTemplate.getPkCoefficientTemplateId());
        }
        //将电视费/煤保置为空
        if (coefficientTemplate.getGasInsurance() == null){
            coefficientTemplateMapper.updateGasInsuranceToNull(coefficientTemplate.getPkCoefficientTemplateId());
        }

        //修改
        coefficientTemplateMapper.updateById(coefficientTemplate);

        return Result.success();
    }

    /**
     * @Description: 查询所有的费用系数模板消息
     * @author zhuliang
     * @date 2020/11/30 19:18
     */
    @Override
    public Result<List<CcmsSmartleasingCoefficientTemplate>> getAllByCoefficient(String token) {
        //查询所有的系数消息
        List<CcmsSmartleasingCoefficientTemplate> coefficientTemplateMapperAll = coefficientTemplateMapper.getAll();

        return Result.success(coefficientTemplateMapperAll);
    }

    /**
     * @Description: 条件查询费用系数模板信息(带分页)
     * @author zhuliang
     * @date 2020/11/26 18:36
     */
    @Override
    public Result<List<CcmsSmartleasingCoefficientTemplate>> conditionalQueryCoefficient(QueryCriteria queryCriteria, String token) {
        //设置分页查询条件
        Page<CcmsSmartleasingCoefficientTemplate> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //设置查询条件对象
        EntityWrapper<CcmsSmartleasingCoefficientTemplate> wrapper = new EntityWrapper<>();
        wrapper.eq("delete_sign", 0)
                .eq(queryCriteria.getCostFactorStatus() != null, "cost_factor_status", queryCriteria.getCostFactorStatus())
                .like(StringUtils.isNotEmpty(queryCriteria.getInputString()), "coefficient_name", queryCriteria.getInputString())
                .orderBy("last_update_date", false)
                .setSqlSelect("pk_coefficient_template_id","coefficient_name","cost_factor_status");

        //开始分页查询
        List<CcmsSmartleasingCoefficientTemplate> templateList = coefficientTemplateMapper.selectPage(toPage, wrapper);

        return Result.success(templateList, toPage.getTotal());
    }
}
